package com.chinacache.maint.webssh.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.StrutsStatics;

import com.chinacache.maint.commons.util.HttpUtil;
import com.chinacache.maint.webssh.ldap.LDAP;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class AuthInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext actionContext = invocation.getInvocationContext();
		HttpServletRequest request = (HttpServletRequest) actionContext
				.get(StrutsStatics.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) actionContext
				.get(StrutsStatics.HTTP_RESPONSE);
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String requestPath = request.getContextPath();
		String requestURI = request.getRequestURI();

		if (requestURI.indexOf("logout.action") != -1) {
			request.getSession().removeAttribute("userName");
			response.sendRedirect("login.action");
			return null;
		}
		if (HttpUtil.getFromSession("userName") != null) {
			return invocation.invoke();
		}
		if (userName == null && password == null) {
			out.print("<html>");
			out.print("<script>");
			out.println("window.open ('" + requestPath + "', '_top')");
			out.println("alert ('请重新登陆！');");
			out.print("</script>");
			out.print("</html>");
			out.close();
			return null;
		}
		if (userName.length() > 0 && password.length() > 0) {
			if (LDAP.userLogin(userName, password)) {
				HttpUtil.putToSession("userName", userName);
				response.sendRedirect("wellcome.action"); 
				return null;
			} else {
				out.print("<html>");
				out.print("<script>");
				out.println("window.open ('" + requestPath + "', '_top')");
				out.println("alert ('用户口令不正确，请重新输入！');");
				out.print("</script>");
				out.print("</html>");
				out.close();
				return null;
			}
		} else {
			// response.sendRedirect("login.action?msg=sdfgsdfg");
			out.print("<html>");
			out.print("<script>");
			out.println("window.open ('" + requestPath + "', '_top')");
			out.println("alert ('请输入用户名和密码！');");
			out.print("</script>");
			out.print("</html>");
			out.close();
			return null;
		}
		// return invocation.invoke();
	}
}
